import maps from '@/utils/maps';
import api from '@/api/api';

// 扁平化菜单列表（用于查找）
function flattenMenuList(menus, result = []) {
  menus.forEach(menu => {
    result.push({
      id: menu.id,
      menu_name: menu.menu_name,
      menu_path: menu.menu_path,
      menu_icon: menu.menu_icon,
      menu_type: menu.menu_type,
      parent_id: menu.parent_id,
    });
    if (menu.children && menu.children.length > 0) {
      flattenMenuList(menu.children, result);
    }
  });
  return result;
}

// 构建菜单树（将平铺数据转换为树形结构）
// 扁平化菜单树（递归处理 children）
function flattenMenuTree(menuTree, result = []) {
  if (!menuTree || !Array.isArray(menuTree)) {
    return result;
  }
  menuTree.forEach(menu => {
    result.push(menu);
    if (menu.children && Array.isArray(menu.children) && menu.children.length > 0) {
      flattenMenuTree(menu.children, result);
    }
  });
  return result;
}

// 判断菜单数据是否已经是树形结构
function isTreeStructure(menus) {
  if (!menus || !Array.isArray(menus) || menus.length === 0) {
    return false;
  }
  // 检查是否有菜单包含 children 字段且 children 是数组
  return menus.some(menu => menu.children && Array.isArray(menu.children) && menu.children.length > 0);
}

function buildMenuTree(flatMenus) {
  if (!flatMenus || !Array.isArray(flatMenus)) {
    return [];
  }
  
  // 如果输入已经是树形结构，先扁平化
  let menus = flatMenus;
  if (isTreeStructure(flatMenus)) {
    menus = flattenMenuTree(flatMenus);
    // 移除 children 字段，因为我们要重新构建
    menus = menus.map(menu => {
      const { children, ...menuWithoutChildren } = menu;
      return menuWithoutChildren;
    });
  }
  
  // 创建菜单映射表，方便查找
  const menuMap = new Map();
  menus.forEach(menu => {
    menuMap.set(menu.id, { ...menu, children: [] });
  });
  
  // 构建树形结构
  const tree = [];
  menus.forEach(menu => {
    const menuNode = menuMap.get(menu.id);
    if (menu.parent_id === 0 || !menu.parent_id) {
      // 顶级菜单
      tree.push(menuNode);
    } else {
      // 子菜单，添加到父菜单的 children 中
      const parent = menuMap.get(menu.parent_id);
      if (parent) {
        if (!parent.children) {
          parent.children = [];
        }
        parent.children.push(menuNode);
      } else {
        // 如果找不到父菜单，作为顶级菜单处理
        tree.push(menuNode);
      }
    }
  });
  
  // 按 sort_order 排序
  const sortMenus = (menus) => {
    menus.sort((a, b) => (a.sort_order || 0) - (b.sort_order || 0));
    menus.forEach(menu => {
      if (menu.children && menu.children.length > 0) {
        sortMenus(menu.children);
      }
    });
  };
  
  sortMenus(tree);
  
  return tree;
}

// 递归过滤和排序菜单树（处理已经是树形结构的数据）
function filterAndSortMenuTree(menuTree, platformFilter) {
  if (!menuTree || !Array.isArray(menuTree)) {
    return [];
  }
  
  const filtered = [];
  menuTree.forEach(menu => {
    // 过滤 platform
    if (platformFilter(menu)) {
      const filteredMenu = { ...menu };
      
      // 递归处理 children
      if (menu.children && Array.isArray(menu.children) && menu.children.length > 0) {
        filteredMenu.children = filterAndSortMenuTree(menu.children, platformFilter);
      } else {
        filteredMenu.children = [];
      }
      
      filtered.push(filteredMenu);
    }
  });
  
  // 按 sort_order 排序
  filtered.sort((a, b) => (a.sort_order || 0) - (b.sort_order || 0));
  
  return filtered;
}

export default {
  namespaced: true,
  state: () => ({
    accountInfo: {},
    userInfo: {},
    menuTree: [], // 完整的菜单树（包括子菜单）- 唯一数据源
    menuLoading: false, // 菜单加载状态
    allButtonPermissions: [], // 所有按钮权限列表（扁平化，用于快速查找）
  }),
  getters: {
    userId: (state) => state.accountInfo.userId,
    userName: (state) => state.accountInfo.userName || '',
    sessionId: (state) => state.accountInfo.sessionId,
    userRole: (state) => state.accountInfo.userRole,
    isSuperAdmin: (state, getters) => getters.userRole === '7',
    userPermission: (state, getters) => {
      console.log('计算userPermission:', {
        isSuperAdmin: getters.isSuperAdmin,
        userInfo: state.userInfo
      });
      return getters.isSuperAdmin ? {} : state.userInfo.permission;
    },
    userGradeList: (state, getters) => {
      console.log('计算userGradeList:', {
        userPermission: getters.userPermission
      });
      const {
        userPermission: { grade_list },
      } = getters;
      return grade_list?.length
        ? JSON.parse(JSON.stringify(grade_list))
        : JSON.parse(JSON.stringify(maps.gradeList));
    },
    userSchoolList: (state, getters) => {
      console.log('计算userSchoolList:', {
        userPermission: getters.userPermission
      });
      const {
        userPermission: { school_list },
      } = getters;
      return school_list?.length ? JSON.parse(JSON.stringify(school_list)) : [];
    },
    userLevl: (state, getters) => {
      console.log('计算userLevl:', {
        userPermission: getters.userPermission
      });
      const {
        userPermission: { level },
      } = getters;
      return level;
    },
    // 获取菜单树
    menuTree: (state) => state.menuTree,
    // 获取用户菜单列表（顶级菜单）- 从 menuTree 计算
    menuList: (state) => {
      return state.menuTree.filter(menu => !menu.menu_type || menu.menu_type === 1);
    },
    // 菜单是否已加载
    menuLoaded: (state) => state.menuTree.length > 0,
    // 所有菜单列表（包括子菜单，扁平化）- 从 menuTree 计算
    allMenuList: (state) => {
      return flattenMenuList(state.menuTree);
    },
    // 根据路由名称获取子菜单
    getChildMenusByRouteName: (state) => (routeName) => {
      if (!routeName || !state.menuTree || !Array.isArray(state.menuTree)) {
        console.log('getChildMenusByRouteName: 参数无效', { routeName, hasMenuTree: !!state.menuTree });
        return [];
      }
      
      console.log('getChildMenusByRouteName: 开始查找路由:', routeName);
      console.log('getChildMenusByRouteName: 菜单树:', state.menuTree);
      
      // 在菜单树中查找匹配的路由
      const findMenu = (menus, targetName) => {
        for (const menu of menus) {
          // 从 menu_path 中提取路由名称
          const menuPath = menu.menu_path || '';
          if (menuPath) {
            const pathParts = menuPath.split('/').filter(part => part && part !== 'homepage');
            if (pathParts.length > 0) {
              const lastPart = pathParts[pathParts.length - 1];
              console.log('getChildMenusByRouteName: 比较菜单路径:', {
                menuName: menu.menu_name,
                menuPath: menuPath,
                lastPart: lastPart,
                targetName: targetName,
                match: lastPart === targetName
              });
              if (lastPart === targetName) {
                console.log('getChildMenusByRouteName: 找到匹配的菜单:', menu);
                return menu;
              }
            }
          }
          
          // 递归查找子菜单
          if (menu.children && Array.isArray(menu.children) && menu.children.length > 0) {
            const found = findMenu(menu.children, targetName);
            if (found) return found;
          }
        }
        return null;
      };
      
      const parentMenu = findMenu(state.menuTree, routeName);
      console.log('getChildMenusByRouteName: 找到的父菜单:', parentMenu);
      
      if (parentMenu && parentMenu.children && Array.isArray(parentMenu.children)) {
        // 过滤掉功能按钮（menu_type === 2），只返回菜单项
        const childMenus = parentMenu.children.filter(child => child.menu_type === 1);
        console.log('getChildMenusByRouteName: 过滤后的子菜单:', childMenus);
        return childMenus;
      }
      
      console.log('getChildMenusByRouteName: 未找到子菜单');
      return [];
    },
    // 获取所有按钮权限（扁平化）
    // 只使用 allButtonPermissions（从接口获取的完整权限列表）
    buttonPermissions: (state) => {
      return state.allButtonPermissions || [];
    },
    // 检查是否有按钮权限（通过 getter 方式）
    hasButtonPermission: (state, getters) => (buttonCode) => {
      if (!buttonCode) return false;
      const buttonPermissions = getters.buttonPermissions;
      return buttonPermissions.some(button => button.menu_path === buttonCode);
    },
  },
  mutations: {
    SET_ACCOUNT_INFO(state, payload) {
      state.accountInfo = payload.value;
    },
    SET_USER_INFO(state, payload) {
      const { value } = payload;
      if (['校务管理员', '校长', '副校长', '教务主任'].includes(value.role)) {
        value.permission.grade_list = [];
        value.permission.class_list = [];
        value.permission.subject_list = [];
      } else if (['年级主任'].includes(value.role)) {
        value.permission.class_list = [];
        value.permission.subject_list = [];
      } else if (['科组长', '备课组长'].includes(value.role)) {
        value.permission.class_list = [];
      }
      state.userInfo = payload.value;
    },
    SET_MENU_TREE(state, menuTree) {
      state.menuTree = menuTree || [];
    },
    SET_MENU_LIST(state, menuList) {
      // SET_MENU_LIST 是 SET_MENU_TREE 的别名，用于兼容旧代码
      state.menuTree = menuList || [];
    },
    SET_MENU_LOADING(state, loading) {
      state.menuLoading = loading;
    },
    CLEAR_MENU_LIST(state) {
      state.menuTree = [];
      state.menuLoading = false;
      state.allButtonPermissions = [];
    },
    SET_ALL_BUTTON_PERMISSIONS(state, permissions) {
      state.allButtonPermissions = permissions || [];
    },
    CLEAR_USER_INFO(state) {
      // 清空 user 模块的 state
      state.accountInfo = {};
      state.userInfo = {};
      state.menuTree = [];
      state.menuLoading = false;
      state.allButtonPermissions = [];
    },
  },
  actions: {
    // 获取用户菜单列表（包括子菜单）
    async fetchUserMenus({ commit, state, getters }) {
      try {
        commit('SET_MENU_LOADING', true);
        
        // 优先使用 accountInfo.userId，这是登录时保存的，更可靠
        const userId = state.accountInfo?.userId || 
                      state.userInfo?.id || 
                      state.userInfo?.F_user_id || 
                      state.userInfo?.user_id;
        
        if (!userId) {
          console.warn('无法获取用户ID，无法加载菜单');
          commit('SET_MENU_TREE', []);
          commit('SET_MENU_LOADING', false);
          return [];
        }
        
        console.log('准备获取用户顶级菜单，用户ID:', userId);
        
        // 调用接口：根据用户ID获取顶级菜单（parent_id=0）
        const params = { F_user_id: userId };
        const response = await api.getTopMenusByUserId(params);
        console.log('获取用户顶级菜单响应:', response);
        
        const { F_responseNo, F_menu_list } = response || {};
        
        if (F_responseNo === 10000 && F_menu_list && Array.isArray(F_menu_list)) {
          // 定义 platform 过滤函数
          const platformFilter = (menu) => {
            // 如果 platform 字段存在且为 1，或者是 undefined/null（兼容旧数据），则保留
            return !menu.platform || menu.platform === 1 || menu.platform === 2; // 暂时兼容 platform = 2
          };
          
          // 过滤平台类型
          const filteredMenus = F_menu_list.filter(platformFilter);
          
          // 顶级菜单列表（只包含 menu_type === 1 的菜单项，排除功能按钮）
          const topMenus = filteredMenus.filter(menu => !menu.menu_type || menu.menu_type === 1);
          
          // 构建菜单树（顶级菜单，children 可能为空或包含初始子菜单）
          // 如果后端返回的数据已经是树形结构，直接使用；否则构建树形结构
          let menuTree;
          if (isTreeStructure(filteredMenus)) {
            console.log('后端返回的是树形结构，直接使用并过滤');
            menuTree = filterAndSortMenuTree(filteredMenus, platformFilter);
          } else {
            console.log('后端返回的是平铺数据，需要构建树形结构');
            // 对于顶级菜单接口，返回的应该都是顶级菜单，直接作为树使用
            menuTree = topMenus.map(menu => ({
              ...menu,
              children: menu.children || [] // 保留已有的 children，如果没有则为空数组
            }));
          }
          
          commit('SET_MENU_TREE', menuTree);
          
          const allMenus = flattenMenuList(menuTree);
          console.log('用户顶级菜单加载成功，顶级菜单数量:', topMenus.length, '总菜单数量:', allMenus.length, '菜单树:', menuTree);
          return menuTree;
        } else {
          console.warn('获取用户菜单失败或菜单为空', {
            F_responseNo,
            F_menu_list,
            menuListType: typeof F_menu_list,
            isArray: Array.isArray(F_menu_list),
            length: Array.isArray(F_menu_list) ? F_menu_list.length : 'N/A'
          });
          commit('SET_MENU_TREE', []);
          return [];
        }
      } catch (error) {
        console.error('获取用户菜单失败:', error);
        commit('SET_MENU_TREE', []);
        return [];
      } finally {
        commit('SET_MENU_LOADING', false);
      }
    },
    
    // 获取用户所有菜单权限（包括所有按钮权限）
    async fetchAllButtonPermissions({ commit, state }) {
      // 优先使用 accountInfo.userId，这是登录时保存的，更可靠
      const userId = state.accountInfo?.userId || 
                    state.userInfo?.id || 
                    state.userInfo?.F_user_id || 
                    state.userInfo?.user_id;
      
      if (!userId) {
        const errorMsg = '无法获取用户ID，无法加载按钮权限';
        console.error(errorMsg);
        throw new Error(errorMsg);
      }
      
      console.log('准备获取用户所有菜单权限（包括按钮），用户ID:', userId);
      
      // 调用接口：根据用户ID获取所有菜单权限（包括所有按钮权限）
      // 添加时间戳参数，避免浏览器或代理缓存
      const params = { 
        F_user_id: userId,
        _t: Date.now() // 时间戳，防止缓存
      };
      const response = await api.getAllMenusByUserId(params);
      console.log('获取用户所有菜单权限响应:', response);
      console.log('获取到的菜单列表数量:', response?.F_menu_list?.length || 0);
      
      // 检查接口响应
      if (!response) {
        const errorMsg = '获取用户所有菜单权限接口无响应';
        console.error(errorMsg);
        throw new Error(errorMsg);
      }
      
      if (response.F_responseNo !== 10000) {
        const errorMsg = `获取用户所有菜单权限失败: ${response.F_responseMsg || '未知错误'} (错误码: ${response.F_responseNo})`;
        console.error(errorMsg, response);
        throw new Error(errorMsg);
      }
      
      const { F_menu_list } = response;
      
      if (!F_menu_list || !Array.isArray(F_menu_list)) {
        const errorMsg = '获取用户所有菜单权限返回数据格式错误';
        console.error(errorMsg, { F_menu_list });
        throw new Error(errorMsg);
      }
      
      // 后端返回的是完整的树形结构（包含所有子菜单和按钮）
      console.log('开始处理菜单数据，菜单总数:', F_menu_list.length);
      
      // 检查数据结构：统计每个顶级菜单的 children 数量
      if (F_menu_list && F_menu_list.length > 0) {
        F_menu_list.forEach((menu, index) => {
          const childrenCount = menu.children && Array.isArray(menu.children) ? menu.children.length : 0;
          console.log(`顶级菜单 ${index + 1} (${menu.menu_name}): children 数量 = ${childrenCount}`, menu);
        });
      }
      
      const isTreeStructure = F_menu_list.some(menu => menu.children && Array.isArray(menu.children) && menu.children.length > 0);
      console.log('菜单数据结构类型:', isTreeStructure ? '树形结构' : '扁平化列表');
      
      // 定义 platform 过滤函数
      const platformFilter = (menu) => {
        return !menu.platform || menu.platform === 1 || menu.platform === 2;
      };
      
      // 过滤平台类型并更新菜单树（因为返回的是完整树形结构，包含所有子菜单和按钮）
      if (isTreeStructure) {
        // 如果是树形结构，直接使用并更新 menuTree
        const filterAndSortMenuTree = (menus, filterFn) => {
          return menus
            .filter(filterFn)
            .map(menu => {
              // 递归处理子菜单
              let filteredChildren = [];
              if (menu.children && Array.isArray(menu.children) && menu.children.length > 0) {
                filteredChildren = filterAndSortMenuTree(menu.children, filterFn);
              }
              
              return {
                ...menu,
                children: filteredChildren
              };
            })
            .sort((a, b) => {
              if (a.sort_order !== b.sort_order) {
                return (a.sort_order || 0) - (b.sort_order || 0);
              }
              return (a.id || 0) - (b.id || 0);
            });
        };
        
        const filteredMenuTree = filterAndSortMenuTree(F_menu_list, platformFilter);
        
        // 验证过滤后的菜单树
        console.log('过滤后的菜单树结构:');
        filteredMenuTree.forEach((menu, index) => {
          const childrenCount = menu.children && Array.isArray(menu.children) ? menu.children.length : 0;
          console.log(`过滤后顶级菜单 ${index + 1} (${menu.menu_name}): children 数量 = ${childrenCount}`);
        });
        
        commit('SET_MENU_TREE', filteredMenuTree);
        console.log('已更新完整菜单树（包含所有子菜单和按钮），顶级菜单数量:', filteredMenuTree.length);
      } else {
        // 如果是扁平化列表，需要构建树形结构（理论上不应该出现，因为后端返回的是树形结构）
        console.warn('后端返回的是扁平化列表，需要构建树形结构');
        commit('SET_MENU_TREE', []);
      }
      
      // 提取按钮权限
      let buttonPermissions = [];
      const flattenAndFilterButtons = (menus, result = []) => {
        if (!menus || !Array.isArray(menus)) {
          return result;
        }
        menus.forEach(menu => {
          // 如果是按钮权限（menu_type === 2），添加到结果中
          if (menu.menu_type === 2) {
            // 移除 children 字段（按钮权限不应该有子项）
            const { children, ...buttonPermission } = menu;
            result.push(buttonPermission);
          }
          // 递归处理子菜单
          if (menu.children && Array.isArray(menu.children) && menu.children.length > 0) {
            flattenAndFilterButtons(menu.children, result);
          }
        });
        return result;
      };
      buttonPermissions = flattenAndFilterButtons(F_menu_list);
      
      commit('SET_ALL_BUTTON_PERMISSIONS', buttonPermissions);
      
      console.log('用户所有按钮权限加载成功，按钮权限数量:', buttonPermissions.length);
      return buttonPermissions;
    },
    
    // 根据菜单ID获取子菜单或功能按钮
    async fetchMenuChildren({ commit, state }, menuId) {
      try {
        if (!menuId) {
          console.warn('菜单ID为空，无法获取子菜单');
          return { children: [], buttons: [] };
        }
        
        const userId = state.accountInfo?.userId || 
                      state.userInfo?.id || 
                      state.userInfo?.F_user_id || 
                      state.userInfo?.user_id;
        
        if (!userId) {
          console.warn('无法获取用户ID，无法加载子菜单');
          return { children: [], buttons: [] };
        }
        
        console.log('准备获取菜单子菜单和功能按钮，菜单ID:', menuId, '用户ID:', userId);
        
        // 调用接口获取子菜单和功能按钮
        const params = { 
          F_user_id: userId,
          F_menu_id: menuId 
        };
        const response = await api.getMenuChildren(params);
        console.log('获取菜单子菜单和功能按钮响应:', response);
        
        const { F_responseNo, F_menu_list } = response || {};
        
        if (F_responseNo === 10000 && F_menu_list && Array.isArray(F_menu_list)) {
          // 分离子菜单（menu_type === 1）和功能按钮（menu_type === 2）
          const children = F_menu_list.filter(menu => menu.menu_type === 1);
          const buttons = F_menu_list.filter(menu => menu.menu_type === 2);
          
          console.log('菜单子菜单和功能按钮加载成功，子菜单数量:', children.length, '功能按钮数量:', buttons.length);
          
          // 更新菜单树中对应菜单的 children
          const updateMenuTree = (menus) => {
            for (const menu of menus) {
              if (menu.id === menuId) {
                // 将子菜单和功能按钮都添加到 children 中（用于菜单树结构）
                menu.children = [...children, ...buttons];
                return menu; // 返回更新的菜单
              }
              if (menu.children && Array.isArray(menu.children) && menu.children.length > 0) {
                const updated = updateMenuTree(menu.children);
                if (updated) return updated;
              }
            }
            return null;
          };
          
          // 创建菜单树的深拷贝并更新
          const menuTree = JSON.parse(JSON.stringify(state.menuTree));
          const updatedMenu = updateMenuTree(menuTree);
          
          console.log('fetchMenuChildren: 更新后的菜单树:', menuTree);
          console.log('fetchMenuChildren: 更新的菜单:', updatedMenu);
          console.log('fetchMenuChildren: 更新的菜单的 children:', updatedMenu?.children);
          
          // 提交更新，这会触发响应式更新
          commit('SET_MENU_TREE', menuTree);
          
          // 强制触发响应式更新（确保 Vue 检测到变化）
          console.log('fetchMenuChildren: 菜单树已更新，新的 menuTree 长度:', menuTree.length);
          
          // allMenuList 和 menuList 现在通过 getter 从 menuTree 计算，不需要单独更新
          console.log('已更新菜单树，子菜单数量:', children.length, '功能按钮数量:', buttons.length);
          
          return { children, buttons, updatedMenu };
        } else {
          console.warn('获取菜单子菜单和功能按钮失败或数据为空', {
            F_responseNo,
            F_menu_list
          });
          return { children: [], buttons: [] };
        }
      } catch (error) {
        console.error('获取菜单子菜单和功能按钮失败:', error);
        return { children: [], buttons: [] };
      }
    },
  },
};
